#include "ThingsBoardClient.h"
#include <LittleFS.h>

ThingsBoardClient::ThingsBoardClient(const String& token, const String& serverIp, int port, const String& deviceName) {
    deviceToken = token;
    serverUrl = "http://" + serverIp + ":" + String(port) + "/api/v1/" + token + "/telemetry";
    this->deviceName = deviceName;
    updateDeviceInfo();
}

void ThingsBoardClient::begin() {
    Serial.println("ThingsBoard Client Initialized.");
}

bool ThingsBoardClient::sendTelemetry(const String& jsonPayload) {
    if (WiFi.status() != WL_CONNECTED) {
        Serial.println("WiFi Disconnected!");
        return false;
    }

    HTTPClient http;
    Serial.printf("Connecting to: %s\n", serverUrl.c_str());
    http.begin(serverUrl); // 设置目标URL
    http.addHeader("Content-Type", "application/json"); // 设置Header

    Serial.printf("Sending Payload: %s\n", jsonPayload.c_str());
    int httpResponseCode = http.POST(jsonPayload); // 发送POST请求
    if (httpResponseCode > 0) {
        Serial.printf("Telemetry Sent! Response Code: %d\n", httpResponseCode);
    } else {
        Serial.printf("Error Sending Telemetry! Response Code: %d\n", httpResponseCode);
    }

    http.end(); // 释放资源
    return httpResponseCode > 0;
}

bool ThingsBoardClient::sendDeviceInfo() {
    if (WiFi.status() != WL_CONNECTED) {
        Serial.println("WiFi Disconnected!");
        return false;
    }

    updateDeviceInfo();

    // 获取存储空间信息
    uint32_t totalStorage = LittleFS.totalBytes();
    uint32_t usedStorage = LittleFS.usedBytes();
    uint32_t freeStorage = totalStorage - usedStorage;

    // 构造JSON数据
    String telemetryData = "{\"device_name\":\"" + deviceName + "\"";
    telemetryData += ",\"ip_address\":\"" + ipAddress + "\"";
    telemetryData += ",\"free_memory\":" + String(ESP.getFreeHeap() / 1024) + "KB";
    telemetryData += ",\"total_memory\":" + String(ESP.getHeapSize() / 1024) + "KB";
    telemetryData += ",\"free_storage\":" + String(freeStorage / 1024) + "KB";
    telemetryData += ",\"total_storage\":" + String(totalStorage / 1024) + "KB";
    telemetryData += "}";

    HTTPClient http;
    Serial.printf("Connecting to: %s\n", serverUrl.c_str());
    http.begin(serverUrl); // 设置目标URL
    http.addHeader("Content-Type", "application/json"); // 设置Header

    Serial.printf("Sending Device Info: %s\n", telemetryData.c_str());
    int httpResponseCode = http.POST(telemetryData); // 发送POST请求
    if (httpResponseCode > 0) {
        Serial.printf("Device Info Sent! Response Code: %d\n", httpResponseCode);
    } else {
        Serial.printf("Error Sending Device Info! Response Code: %d\n", httpResponseCode);
    }

    http.end(); // 释放资源
    return httpResponseCode > 0;
}

void ThingsBoardClient::updateDeviceInfo() {
    if (WiFi.status() == WL_CONNECTED) {
        ipAddress = WiFi.localIP().toString();
    } else {
        ipAddress = "Not Connected";
    }
}